from venv import logger

from casdoor.resource import Resource
from fastapi import APIRouter, Request
from fastapi import Depends
from config.get_db import get_db
from module_admin.dao.resource_dao import ResourceDao
from module_admin.service.login_service import get_current_user, get_current_user_details
from module_admin.service.menu_service import *
from module_admin.entity.vo.menu_vo import *
from module_admin.dao.menu_dao import *
from utils.response_util import *
from utils.log_util import *
from module_admin.aspect.interface_auth import CheckUserInterfaceAuth
from module_admin.annotation.log_annotation import log_decorator
from config.config import Config

menuController = APIRouter(dependencies=[Depends(get_current_user_details)])


@menuController.post("/menu/tree", response_model=MenuTree, dependencies=[Depends(CheckUserInterfaceAuth('common'))])
async def get_system_menu_tree(request: Request, menu_query: MenuTreeModel, query_db: Session = Depends(get_db),
                               current_user: CurrentUserInfoServiceResponse = Depends(get_current_user)):
    try:
        menu_query_result = MenuService.get_menu_tree_services(query_db, menu_query, current_user)
        logger.info('获取成功')
        return response_200(data=menu_query_result, message="获取成功")
    except Exception as e:
        logger.exception(e)
        return response_500(data="", message=str(e))


@menuController.post("/menu/forEditOption", response_model=MenuTree,
                     dependencies=[Depends(CheckUserInterfaceAuth('common'))])
async def get_system_menu_tree_for_edit_option(request: Request, menu_query: MenuModel,
                                               query_db: Session = Depends(get_db),
                                               current_user: CurrentUserInfoServiceResponse = Depends(
                                                   get_current_user)):
    try:
        menu_query_result = MenuService.get_menu_tree_for_edit_option_services(query_db, menu_query, current_user)
        logger.info('获取成功')
        return response_200(data=menu_query_result, message="获取成功")
    except Exception as e:
        logger.exception(e)
        return response_500(data="", message=str(e))


@menuController.post("/menu/get", response_model=MenuResponse,
                     dependencies=[Depends(CheckUserInterfaceAuth('system:menu:list'))])
async def get_system_menu_list(request: Request, menu_query: MenuModel, query_db: Session = Depends(get_db),
                               current_user: CurrentUserInfoServiceResponse = Depends(get_current_user)):
    try:
        menu_query_result = MenuService.get_menu_list_services(query_db, menu_query, current_user)
        logger.info('获取成功')
        return response_200(data=menu_query_result, message="获取成功")
    except Exception as e:
        logger.exception(e)
        return response_500(data="", message=str(e))


@menuController.post("/menu/add", response_model=CrudMenuResponse,
                     dependencies=[Depends(CheckUserInterfaceAuth('system:menu:add'))])
@log_decorator(title='菜单管理', business_type=1)
async def add_system_menu(request: Request, add_menu: MenuModel, query_db: Session = Depends(get_db),
                          current_user: CurrentUserInfoServiceResponse = Depends(get_current_user)):
    try:
        add_menu.create_by = current_user.user.user_name
        add_menu.update_by = current_user.user.user_name
        add_menu_result = MenuService.add_menu_services(query_db, add_menu)
        if add_menu_result.is_success:
            logger.info(add_menu_result.message)
            return response_200(data=add_menu_result, message=add_menu_result.message)
        else:
            logger.warning(add_menu_result.message)
            return response_400(data="", message=add_menu_result.message)
    except Exception as e:
        logger.exception(e)
        return response_500(data="", message=str(e))


@menuController.patch("/menu/edit", response_model=CrudMenuResponse,
                      dependencies=[Depends(CheckUserInterfaceAuth('system:menu:edit'))])
@log_decorator(title='菜单管理', business_type=2)
async def edit_system_menu(request: Request, edit_menu: MenuModel, query_db: Session = Depends(get_db),
                           current_user: CurrentUserInfoServiceResponse = Depends(get_current_user)):
    try:
        edit_menu.update_by = current_user.user.user_name
        edit_menu.update_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        edit_menu_result = MenuService.edit_menu_services(query_db, edit_menu)
        if edit_menu_result.is_success:
            logger.info(edit_menu_result.message)
            return response_200(data=edit_menu_result, message=edit_menu_result.message)
        else:
            logger.warning(edit_menu_result.message)
            return response_400(data="", message=edit_menu_result.message)
    except Exception as e:
        logger.exception(e)
        return response_500(data="", message=str(e))


@menuController.post("/menu/delete", response_model=CrudMenuResponse,
                     dependencies=[Depends(CheckUserInterfaceAuth('system:menu:remove'))])
@log_decorator(title='菜单管理', business_type=3)
async def delete_system_menu(request: Request, delete_menu: DeleteMenuModel, query_db: Session = Depends(get_db)):
    try:
        delete_menu_result = MenuService.delete_menu_services(query_db, delete_menu)
        if delete_menu_result.is_success:
            logger.info(delete_menu_result.message)
            return response_200(data=delete_menu_result, message=delete_menu_result.message)
        else:
            logger.warning(delete_menu_result.message)
            return response_400(data="", message=delete_menu_result.message)
    except Exception as e:
        logger.exception(e)
        return response_500(data="", message=str(e))


@menuController.get("/menu/{menu_id}", response_model=MenuModel,
                    dependencies=[Depends(CheckUserInterfaceAuth('system:menu:query'))])
async def query_detail_system_menu(request: Request, menu_id: int, query_db: Session = Depends(get_db)):
    try:
        detail_menu_result = MenuService.detail_menu_services(query_db, menu_id)
        logger.info(f'获取menu_id为{menu_id}的信息成功')
        return response_200(data=detail_menu_result, message='获取成功')
    except Exception as e:
        logger.exception(e)
        return response_500(data="", message=str(e))


@menuController.post("/menu/cas/add", summary="casdoor菜单添加")
async def casdoor_menu_add(casdoor_menu_for_add: CasdoorMenuForAdd):
    try:
        resource = Resource()
        resource.name = "/" + casdoor_menu_for_add.name
        resource.createdTime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())
        resource.application = Config.sdk.application_name
        resource.parent = casdoor_menu_for_add.parent
        resource.url = casdoor_menu_for_add.url
        resource.description = casdoor_menu_for_add.remark
        Config.sdk.add_resource(resource)
        return response_200(data="", message='新增成功')
    except Exception as e:
        logger.exception(e)
        return response_500(data="", message=str(e))


@menuController.post("/menu/cas/edit", summary="casdoor菜单编辑")
async def casdoor_menu_edit(casdoor_menu_for_add: CasdoorMenuForAdd):
    try:
        resource: Resource = Config.sdk.get_resource(casdoor_menu_for_add.name)
        if casdoor_menu_for_add.name is not None and len(casdoor_menu_for_add.name) != 0:
            resource.name = "/" + casdoor_menu_for_add.name
        if casdoor_menu_for_add.parent is not None and len(casdoor_menu_for_add.parent) != 0:
            resource.parent = casdoor_menu_for_add.parent
        if casdoor_menu_for_add.url is not None and len(casdoor_menu_for_add.url) != 0:
            resource.url = casdoor_menu_for_add.url
        if casdoor_menu_for_add.remark is not None and len(casdoor_menu_for_add.remark) != 0:
            resource.description = casdoor_menu_for_add.remark
        Config.sdk.update_resource(resource)
        return response_200(data="", message='修改成功')
    except Exception as e:
        logger.exception(e)
        return response_500(data="", message=str(e))


@menuController.post("/menu/cas/delete/{name}", summary="casdoor菜单删除")
async def casdoor_menu_delete(name: str, db: Session = Depends(get_db)):
    try:
        ResourceDao.delete_driver_by_owner_and_name(db, Config.sdk.org_name, "/" + name)
        return response_200(data="", message='删除成功')
    except Exception as e:
        logger.exception(e)
        return response_500(data="", message=str(e))


@menuController.get("/menu/cas/tree", response_model=CasdoorMenuForTree, summary="casdoor菜单树")
async def casdoor_menu_tree():
    try:
        tree = MenuService.get_menu_tree_casdoor()
        return response_200(data=tree, message='获得成功')
    except Exception as e:
        logger.exception(e)
        return response_500(data="", message=str(e))
